<?php
declare(strict_types=1);

namespace App\Libs;
use OSS\OssClient;
use OSS\Core\OssException;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
use AlibabaCloud\Sts\Sts;
use Hyperf\Cache\Annotation\Cacheable;
use Hyperf\Utils\Context;
use OSS\Credentials\StaticCredentialsProvider;

class Oss
{
    protected static $accessKeyId = "LTAI5tHR7o1nb412pdzpjf94";
    protected static $accessKeySecret = "uLkwZ8UGMMOxp1bXqw2QJ137FWHv5M";
    public static $endpoint = "https://oss-cn-beijing.aliyuncs.com";//-internal
    public static $endpoint_url = "https://podfinaly.oss-cn-beijing.aliyuncs.com/";
    protected static $bucket = "podfinaly";

    public static function getObject($key) {
        try {

            $provider = new StaticCredentialsProvider(self::$accessKeyId, self::$accessKeySecret);
            // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
            // 填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
            // 填写Bucket名称，例如examplebucket。
            // 如果图片位于Bucket根目录，则直接填写图片名称。如果图片不在Bucket根目录，需携带图片完整路径，例如exampledir/example.jpg。

            $config = array(
                "provider" => $provider,
                "endpoint" => self::$endpoint,        
                "signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
                // 填写阿里云通用Region ID。
                "region" => "cn-beijing"
            );
            $ossClient = new OssClient($config);
            // 构建获取图片信息的处理指令。
            $options[$ossClient::OSS_PROCESS] = "image/info";
            $result = $ossClient->getObject(self::$bucket,$key,$options);
            return $result;
        } catch (OssException $e) {
            printf($e->getMessage() . "\n");
            return;
        }
    }
    
    
    public static function getToken()
    {
        AlibabaCloud::accessKeyClient(self::$accessKeyId, self::$accessKeySecret)->regionId('cn-shanghai')->asDefaultClient();
        try {
            $request = Sts::V20150401()->assumeRole();
            $result = $request
                ->withRoleArn("acs:ram::31061645:role/image")
                ->withRoleSessionName("image")
                ->connectTimeout(1) // Throw an exception when Connection timeout
                ->timeout(1) // Throw an exception when timeout 
                ->request();
                // var_dump($result);
            return ($result->toArray());
        } catch (ClientException $exception) {
            var_dump($exception);
            echo $exception->getMessage() . PHP_EOL;
            return [];
        } catch (ServerException $exception) {
            var_dump($exception);
            echo $exception->getMessage() . PHP_EOL;
            echo $exception->getErrorCode() . PHP_EOL;
            echo $exception->getRequestId() . PHP_EOL;
            echo $exception->getErrorMessage() . PHP_EOL;
            return [];
        }
    }

    public static function getSignature($config){
        $now = time();
        $expire = 3600 * 3;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = self::gmt_iso8601($end);
        
        $condition = array(0 => 'content-length-range', 1 => 0, 2 => 1048576000);
        $conditions[] = $condition;
        $dir = 'uploads/users/';
        $conditions[] = ['starts-with', '$key', $dir];

        $start = array(0 => 'starts-with', 1 => '$key', 2 => 'house');
        $conditions[] = $start;

        $arr = array('expiration' => $expiration, 'conditions' => $conditions);
        $policy = base64_encode(json_encode($arr));
        $signature = base64_encode(hash_hmac('sha1', $policy, $config['Credentials']['AccessKeySecret'], true));
        // $signature = base64_encode(hash_hmac('sha1', $policy, config('file.storage.oss.accessSecret'), true));

        $security_token = $config['Credentials']['SecurityToken'];
        $expiration = ($config['Credentials']['Expiration']);//strtotime
        $accessKeyId =  $config['Credentials']['AccessKeyId'];
        return compact('policy', 'signature', 'security_token', 'expiration', 'accessKeyId');

    }
    protected static function gmt_iso8601($time){
        return str_replace('+00:00', '.000Z', gmdate('c', $time));
    }
}